/*
 *   MacOS will not support a script as a CFBundleExecutable target, so this
 *   executable can be used in its place.
 *   
 *   Name the executable "program-desync" and it will execute "program" with
 *   the appropriate settings
 *   
 *   In order to make this work with an Application Bundle (AKA ".app"), change
 *   the app's Contents/Info.plist to append "-desync" to CFBundleExecutable 
 *   (/usr/libexec/PlistBuddy is your friend) and place both this wrapper, with
 *   the appropriate name, and libdesync.dylib inside the Contents/MacOS
 *   directory.
 *   
 *   MacOS seeme to cache the Info.plist file somewhere.  The easiest way I've
 *   found to clear it is to open the bundle's Info panel in the Finder, rename
 *   it something other than ".app", then rename it back.
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <libgen.h>

int main(int argc, char *argv[]) {
	int offset;
	char *libname;

	offset = strlen(argv[0]) - 7;  // 7 == strlen("-desync")
	if (strcmp(&argv[0][offset], "-desync") != 0) {
		fprintf(stderr, "wrapper-desync not installed properly\n");
		exit(1);
	}
	argv[0][offset] = '\0';
	libname = strdup(dirname(argv[0]));
	libname = realloc(libname, strlen(libname) + 16); // 16 == strlen("/libdesync.dylib")
	strcat(libname, "/libdesync.dylib");
	setenv("DYLD_INSERT_LIBRARIES", libname, 1);
	fprintf(stderr, "wrapper-desync running: DYLD_INSERT_LIBRARIES=%s %s\n", libname, argv[0]);
	execvp(argv[0], argv);
	perror("wrapper-desync cannot execute target");
	exit(2);
}
